#!/bin/sh

APPATH=${APPATH:-".:./bin:./lib:/opt/mysql/lib"}
#SILENT=1
include_1()
{
	WANTED=$1
	if [ "${WANTED:0:1}" = "/" -a -r "$WANTED" ]; then
		echo "Sourcing: $WANTED"
		source $WANTED
		uniqInclude $WANTED
		return 0
	fi 

	for p in $(echo $APPATH| tr ':' ' '); do
		if [ -r "$p/$WANTED" ]; then
			WANTED=$(readlink -f "$p/$WANTED")
			echo "Sourcing: $WANTED"
			source "$WANTED"
			uniqInclude $WANTED
			return 0
		fi
	done
	echo "Warning for resource '$WANTED' in ( $(echo $APPATH| tr ':' ' ')  )"
	return 1
}
uniqInclude()
{
	INCLUDED=$(echo "$INCLUDED $WANTED"| sed -e 's/ /\n/g' | sort | uniq)
}
isAlreadyIncluded()
{
	WANTED=$1
	if [ "${WANTED:0:1}" = "/" -a -r "$WANTED" ]; then
		echo "$INCLUDED" | grep -q "$WANTED"
		if [ $? -eq 0 ]; then
			echo "$1 already included...."
			return 0
		fi
	fi
	for p in $(echo $APPATH| tr ':' ' '); do
		if [ -r "$p/$WANTED" ]; then
			WANTED=$(readlink -f "$p/$WANTED")
			echo "$INCLUDED" | grep -q "$WANTED"
			if [ $? -eq 0 ]; then
				echo "$1 already included...."
				return 0
			fi
		fi
	done
	
	echo "$1 never included...."
	return 1 
}

require()
{
	RC=0
	for elt in $@; do
		include_1 $elt
		if [ $? -ne 0 ]; then
			echo "Stopping because I cant find requirement '$elt' in ( $(echo $APPATH| tr ':' ' ')  )"
			return 1
		fi
	done
	return 0
}
include() 
{
	RC=0
	for elt in $@; do
		include_1 $elt
		TMP=$?;RC=$((RC+TMP))
	done
	if [ $RC -gt 0 ]; then
		echo "$RC include warning(s) found."
	fi
	return $RC 
}


require_once()
{
	RC=0
	for elt in $@; do
		isAlreadyIncluded $elt 
		if [ $? -eq 0 ]; then
			echo "Stopping because '$elt' already included in ( $(echo $APPATH| tr ':' ' ')  )"
			continue
		fi
		include_1 $elt
		if [ $? -ne 0 ]; then
			echo "Stopping because I cant find requirement '$elt' in ( $(echo $APPATH| tr ':' ' ')  )"
			return 1
		fi
	done
	return 0
}
include_once() 
{
	RC=0
	for elt in $@; do
		isAlreadyIncluded $elt && continue
		include_1 $elt
		TMP=$?;RC=$((RC+TMP))
	done
	if [ $RC -gt 0 ]; then
		echo "$RC include warning(s) found."
	fi
	return $RC 
}


true
